<template>
  <main>
    <div>
      <el-upload
        :http-request="customUpload"
        action=""
        multiple
        :on-exceed="handleExceed"
        :before-upload="beforeUpload"
        :on-success="handleSuccess"
        :file-list="fileList"
        :limit="NumberOfPictures"
      >
        <el-space>
          <el-button plain :icon="FolderOpened">文件夹批量上传</el-button>
          <el-button plain :icon="FolderAdd">单个文件上传</el-button>
        </el-space>
      </el-upload>
    </div>
  </main>
</template>

<script setup>
/**
 *
 */
import { onMounted, reactive, ref } from "vue";
/**
 *
 */
import { ElMessage } from "element-plus";
/**
 *
 */
import { FolderOpened, FolderAdd } from "@element-plus/icons-vue";

/**
 * 存储
 */
import storageService from "@/utils/dataStore_utils";
/**
 * 训练集
 */
import FileUploadApi from "@/api/modules/FileUploadApi";
/**
 *
 */
import { requestedMessage } from "@/utils/requested_utils";
/**
 *
 */
const fileList = ref([]);
/**
 * 图片数量
 */
const NumberOfPictures = ref(10000);

// 文件超出限制时的处理
const handleExceed = (files, uploadFiles) => {
  console.log("图片", files, "-------", uploadFiles);
};

// 上传前的校验
const beforeUpload = (rawFile) => {
  console.log("文件信息", rawFile);

  // 检查文件类型
  const isImage = ["image/jpeg", "image/png", "image/webp"].includes(
    rawFile.type
  );
  // 检查文件大小
  const isLt2M = rawFile.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("上传图片只能是 JPG、PNG 或 WEBP 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 自定义上传方法
const customUpload = ({ file }) => {
  const formData = new FormData();
  formData.append("file", file); // 添加文件到表单数据

  // 动态设置每个文件的上传路径和其他参数
  const filePath = `${storageService.sessionData.PicturePath}/${file.name}`;
  formData.append("id", storageService.sessionData.TheDataSetid);
  formData.append("path", filePath);

  requestedMessage(
    async () => {
      const { message, msg } = await FileUploadApi.uploadResource(formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });

      return msg;
    },
    {
      showSuccess: true,
      fullscreenLoading: true,
    }
  );
};

// 上传成功后的处理
const handleSuccess = (response, uploadFile) => {
  switch (response.status) {
    case 200:
      ElMessage.success(response.msg);
      break;
    default:
      ElMessage.error(response.msg);
      break;
  }
  console.log("上传成功", response, uploadFile);
};
</script>
